package com.lw.shiro.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lw.service.UserService;
import com.lw.system.ProfileResult;
import com.lw.system.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

public class UserRealm extends HrmRealm {
    @Autowired
    UserService userService;
    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
        //获取用户名和密码
        String mobile = token.getUsername();
        String password = new String( token.getPassword() );
        //根据手机号查找用户
        User user = userService.getOne( new QueryWrapper<User>().eq( "mobile", mobile ) );
        User byId = userService.findById( user.getId() );
        if (user!=null&&user.getPassword().equals( password )){//判断用户是否存在 并且密码一致
            //如果成功 存入安全数据
            ProfileResult profileResult = new ProfileResult( byId );
            SimpleAuthenticationInfo info=new SimpleAuthenticationInfo( profileResult,user.getPassword(),this.getName() );
            return info;
        }else {
            //不成功 抛出异常
            // return null（抛出异常）
            return null;
        }
    }
}
